$(() => {
    // 显示购物车信息
    if (userInfo) {
        // 用户登录
        $.ajax({
            url: wurl + '/cart/lists',
            data: { userId: userInfo.id },
            success: function (response) {
                showUserCart(response.data);
            }
        });

    } else {
        // 用户未登录
        let userCart = localStorage.getItem('userCart') ? JSON.parse(localStorage.getItem('userCart')) : {};
        let goodsIds = Object.keys(userCart);
        if (goodsIds.length > 0) {
            $.ajax(wurl + '/goods/getGoodsByIds', JSON.stringify({ goodsIds }), response => {
                console.log(response);
            })
            $.ajax({
                url: wurl + '/goods/getGoodsByIds',
                type: 'post',
                contentType: 'application/json',
                data: JSON.stringify({ goodsIds }),
                success: function (response) {
                    let data = [];
                    response.data.forEach(item => {
                        data.push({
                            goodsId: item.id,
                            goods: item,
                            goodsCount: userCart[item.id]
                        });
                    });
                    showUserCart(data);
                }
            });
        }
    }

    // 删除
    $('.mycart').on('click', '.delete', function () {
        if (userInfo) {
            $.get(wurl + '/cart/remove', { userId: userInfo.id, cartId: $(this).parent().parent().attr('data-cartid') }, response => {
                $(this).parent().parent().remove();
                if ($(this).parent().siblings('.col7').find('input').prop('checked')) {
                    let goodsId = $(this).parent().parent().attr('data-goodsid');
                    let checkedBox = JSON.parse(localStorage.getItem('checkedBox'));
                    delete checkedBox[goodsId];
                    localStorage.setItem('checkedBox', JSON.stringify(checkedBox));
                    checkBox();
                }
            })
        } else {
            let userCart = localStorage.getItem('userCart') ? JSON.parse(localStorage.getItem('userCart')) : {};
            let goodsId = $(this).parent().parent().attr('data-goodsid');
            delete userCart[goodsId];
            localStorage.setItem('userCart', JSON.stringify(userCart));
            $(this).parent().parent().remove();
            if ($(this).parent().siblings('.col7').find('input').prop('checked')) {
                let goodsId = $(this).parent().parent().attr('data-goodsid');
                let checkedBox = JSON.parse(localStorage.getItem('checkedBox'));
                delete checkedBox[goodsId];
                localStorage.setItem('checkedBox', JSON.stringify(checkedBox));
                checkBox();
            }
        }
    })

    // 商品数量加减(加减号的)
    $('tbody').on('click', 'tr>.col4>a', function () {
        let goodsId = parseInt($(this).parent().parent().attr('data-goodsid'));
        let goodsCount = 1;
        if (userInfo) {
            goodsCount = addORreduce(this);
            $.ajax({
                url: wurl + '/cart/add',
                type: 'post',
                contentType: 'aplication/json',
                data: JSON.stringify({ userId: userInfo.id, goodsId, goodsCount }),
                success: response => {
                }
            });
            // 小计重新渲染
            let shopPrice = $(this).parent().attr('shopprice');
            $(this).parent().next().find('span').html(shopPrice * goodsCount);
        } else {
            goodsCount = addORreduce(this);
            let userCart = localStorage.getItem('userCart') ? JSON.parse(localStorage.getItem('userCart')) : {};
            if (userCart[goodsId]) {
                userCart[goodsId] = goodsCount + parseInt(userCart[goodsId]);
            } else {
                userCart[goodsId] = goodsCount;
            }
            localStorage.setItem('userCart', JSON.stringify(userCart));
            // 小计重新渲染
            let shopPrice = $(this).parent().attr('shopprice');
            $(this).parent().next().find('span').html(shopPrice * goodsCount);
        }
        if ($(this).parent().siblings('.col7').find('input').prop('checked')) {
            checkBox();
        }
    });
    function addORreduce(_this) {
        if ($(_this).prop('class') == 'add_num') {
            let goodsCount = parseInt($(_this).prev().val());
            $(_this).prev().val(++goodsCount);
            return goodsCount;
        } else if ($(_this).prop('class') == 'reduce_num') {
            let goodsCount = parseInt($(_this).next().val());
            goodsCount > 1 ? $(_this).next().val(--goodsCount) : layer.msg('不能再减啦');
            return goodsCount;
        }
    }
    // 商品数量改变(输入框中)
    $('tbody').on('change', 'tr>.col4>input', function () {
        let goodsCount = parseInt($(this).val());
        if (goodsCount <= 0) {
            $(this).val(1);
            goodsCount = 1;
            layer.msg('主人留下一个吧');
        }
        let goodsId = parseInt($(this).parent().parent().attr('data-goodsid'));
        if (userInfo) {
            $.ajax({
                url: wurl + '/cart/add',
                type: 'post',
                contentType: 'aplication/json',
                data: JSON.stringify({ userId: userInfo.id, goodsId, goodsCount }),
                success: response => {
                }
            });
            // 小计重新渲染
            let shopPrice = $(this).parent().attr('shopprice');
            $(this).parent().next().find('span').html(shopPrice * goodsCount);
        } else {
            let userCart = localStorage.getItem('userCart') ? JSON.parse(localStorage.getItem('userCart')) : {};
            if (userCart[goodsId]) {
                userCart[goodsId] = goodsCount + parseInt(userCart[goodsId]);
            } else {
                userCart[goodsId] = goodsCount;
            }
            localStorage.setItem('userCart', JSON.stringify(userCart));
            // 小计重新渲染
            let shopPrice = $(this).parent().attr('shopprice');
            $(this).parent().next().find('span').html(shopPrice * goodsCount);
        }
        if ($(this).parent().siblings('.col7').find('input').prop('checked')) {
            checkBox();
        }
    });

    // 勾选后显示勾选总金额
    $('tbody').on('click', 'tr>.col7>input', function () {
        checkBox();
        let goodsId = $(this).parent().parent().attr('data-goodsid');
        let checkedBox = localStorage.getItem('checkedBox') ? JSON.parse(localStorage.getItem('checkedBox')) : {};
        $(this).prop('checked')?(checkedBox[goodsId] = 1):(delete checkedBox[goodsId]);
        localStorage.setItem('checkedBox', JSON.stringify(checkedBox));
    });
    function checkBox() {
        let total = 0;
        $('input[class="selectBox"]:checked').each((index, item) => {
            total += parseFloat($(item).parent().siblings('.col5').find('span').html());
        });
        $('#total').html(total);
    }


    // 结算
    $('.checkout').on('click', () => {
        if (userInfo) {

        } else {
            // 获取到当前被勾选的商品:$('input[class="selectBox"]:checked')
            // 计算被勾选的商品的id数组
            let selectGoodsIds = [];
            $('input[class="selectBox"]:checked').each((index, item) => {
                selectGoodsIds.push($(item).attr('data-goodsid'));
            });
            let backUrl = encodeURIComponent(location.href + '?selectGoodsIds=' + selectGoodsIds.join(','));
            location.href = 'login.html?back=' + backUrl;
        }
    });

    // 展示购物车
    function showUserCart(data) {
        // 获取用户登录前勾选的商品id
        let selectGoodsIds = getUrlParam('selectGoodsIds') ? getUrlParam('selectGoodsIds').split(',') : [];
        history.pushState(null, null, 'flow1.html');
        let checkedBox = localStorage.getItem('checkedBox') ? JSON.parse(localStorage.getItem('checkedBox')) : {};
        let html = '';
        data.forEach(item => {
            html += `<tr data-cartid="${item.id}" data-goodsid="${item.goodsId}">
                <td class="col7"><input type="checkbox" class="selectBox" data-goodsid="${item.goodsId}" ${(selectGoodsIds.includes((item.goodsId).toString()) || checkedBox[item.goodsId]) ? 'checked' : ''} /></td>
                <td class="col1"><a href=""><img src="${item.goods.goodsThumb}" alt="" /></a>  <strong><a href="">${item.goods.goodsName}</a></strong></td>
                <td class="col3">￥<span>${item.goods.shopPrice}</span></td>
                <td class="col4" shopprice="${item.goods.shopPrice}"> 
                    <a href="javascript:;" class="reduce_num"></a>
                    <input type="text" name="amount" value="${item.goodsCount}" class="amount"/>
                    <a href="javascript:;" class="add_num"></a>
                </td>
                <td class="col5">￥<span>${item.goodsCount * item.goods.shopPrice}</span></td>
                <td class="col6"><a href="javascript:;"  class="delete">删除</a></td>
            </tr>`;
        });
        $('.mycart tbody').html(html);
        checkBox();
    }
});